package google;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;

/**
 * Google Guava
 * 本地缓存<br/>
 * @author Administrator
 *
 */
public class GoogleGuavaManage {

	// 初始化线程池
	private final ExecutorService executor = Executors.newFixedThreadPool(3);

	private LoadingCache<String, Student> cache;

	private final ArrayList<ListenNumsTask> threadPool = new ArrayList<ListenNumsTask>();
	
	public void init() {
		
		for(int i=0; i < 5;i++){
			ListenNumsTask task = new ListenNumsTask();
			threadPool.add(task);
		}
		
		cache = CacheBuilder.newBuilder().maximumSize(100)
				// 设置写缓存后8秒钟过期
				.expireAfterWrite(20, TimeUnit.SECONDS)
				//设置缓存刷新时间
				.refreshAfterWrite( 45, TimeUnit.SECONDS )
				// 设置缓存的移除通知
				.removalListener(new RemovalListener<Object, Object>() {
					public void onRemoval(RemovalNotification<Object, Object> notification) {
						System.out.println(notification.getKey() + " was removed, cause is " + notification.getCause());
					}
				}).build(new CacheLoader<String, Student>() {
					@Override
					public Student load(String key) throws Exception {
						System.out.println("=================开始调用3  load();=========================" + System.currentTimeMillis());
						Student stu = new Student();
						stu.setId(1);
						stu.setName("lyl1");
						return stu;
					}
					//当现有的缓存刷新的时候调用这个方法
					@Override
					public ListenableFuture<Student> reload(String key, Student oldVal) {
						System.out.println("=================开始调用4 reload();=========================" + System.currentTimeMillis());
						ListenableFutureTask<Student> task = ListenableFutureTask.create(new Callable<Student>() {
							public Student call() throws Exception {
								Student stu = new Student();
								stu.setId(1);
								stu.setName("lyl2");
								return stu;
							}
						});
						executor.execute(task);
						return task;
					}
				});
	}

	public Student getStudent() {
		try {
			return cache.get("kkk");
		} catch (Exception e) {

		}
		return null;
	}
}
